<?php
// +----------------------------------------------------------------------
// | Yzncms [ 御宅男工作室 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2018 http://yzncms.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 御宅男 <530765310@qq.com>
// +----------------------------------------------------------------------

// +----------------------------------------------------------------------
// | 用户自定义函数库
// +----------------------------------------------------------------------
use EasyWeChat\Factory;
use think\Db;
use think\Image;
use think\facade\Session;


use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
use AlibabaCloud\Tea\Exception\TeaError;
use AlibabaCloud\Tea\Utils\Utils;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;

//use App\Lib\Config\SmsKeyConstant;
use Darabonba\OpenApi\Models\Config;

//use Exception;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use think\Validate;

function sendAliyunSms($phone, $signName, $templateCode, $templateParam)
{
    // 初始化客户端
    AlibabaCloud::accessKeyClient(
        'LTAI5tQ79ZzCBiyFGKZiAFdv',      // 替换为你的AccessKey ID
        'B9k5lUrPhX68IFaBUqSrt70r08HEMz'   // 替换为AccessKey Secret
    )->regionId('cn-hangzhou')     // 默认杭州区域
    ->asDefaultClient();

    try {
        $result = AlibabaCloud::rpc()
            ->product('Dysmsapi')
            ->version('2017-05-25')
            ->action('SendSms')
            ->method('POST')
            ->host('dysmsapi.aliyuncs.com')
            ->options([
                'query' => [
                    'PhoneNumbers' => $phone,
                    'SignName' => $signName,
                    'TemplateCode' => $templateCode,
                    'TemplateParam' => json_encode($templateParam),
                ],
            ])
            ->request();
        return $result->toArray();
    } catch (ClientException $e) {
        return ['error' => $e->getErrorMessage()];
    } catch (ServerException $e) {
        return ['error' => $e->getErrorMessage()];
    }
}

function conf($val = "", $vals = "")
{
    return config()[$val][$vals];
}

function responseJson($code = 0, $msg = '', $data = null)
{
    $response = array(
        'code' => $code,
        'data' => $data,
        'msg' => $msg
    );
    exit(json_encode($response));
}

function lmcurl($url)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_FAILONERROR, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_AUTOREFERER, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 5);
    $SSL = substr($url, 0, 8) == "https://" ? true : false;
    if ($SSL) {
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 信任任何证书
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); // 检查证书中是否设置域名
    }
    $content = curl_exec($ch);
    curl_close($ch);
    return $content;
}

function msg($code = 0, $msg = "", $data, $count = 1)
{

    $res['code'] = $code;

    $res['msg'] = $msg;

    $res['data'] = $data;

    $res['count'] = $count;

    exit(arj($res));

}

function arj($data, $isformdata = 1)
{
    if ($data == '' || empty($data)) return '';

    // if($isformdata) $data = new_stripslashes($data);

    if (version_compare(PHP_VERSION, '5.3.0', '<')) {
        return json_encode($data, JSON_UNESCAPED_UNICODE);
    } else {
        return json_encode($data, JSON_UNESCAPED_UNICODE);
    }
}

/**
 * 获取微信小程序token
 * @return bool|string
 */
function getAccessToken()
{
    $appid = config('wechat.appID');
    $secret = config('wechat.AppSecret');
    $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $secret;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);

    curl_setopt($ch, CURLOPT_HEADER, 0);

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    $res = curl_exec($ch);
    curl_close($ch);
    return $res;
}

function getDistance($from, $to)
{
//
    $lastPos = strrpos($to, ';');
    if ($lastPos !== false) {
        $to = explode(';', $to)[1];
    }
//
    $to = explode(',', $to);

    $from = explode(',', $from);

    $radLat1 = deg2rad(floatval($to[1]));// deg2rad()函数将角度转换为弧度

    $radLat2 = deg2rad(floatval($from[1]));

    $radLng1 = deg2rad(floatval($to[0]));

    $radLng2 = deg2rad(floatval($from[0]));

    $a = $radLat1 - $radLat2;

    $b = $radLng1 - $radLng2;

    $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2))) * 6378.137;

    return round($s, 2);
}

//通过IP获取地址
function getDistrictByIP($ip)
{
    $url = "http://ip-api.com/json/" . $ip;
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    curl_close($ch);

    $data = json_decode($response, true);
    if ($data && $data['status'] === 'success') {
        return $data['city']; // 返回区县名
    } else {
        return 'Unknown';
    }
}

//获取订单号
function GetOrderSN($type, $data = array())
{

    if ($type == 1) {


        $city_code = cityCode($data);

        $time = date('ymd');

        $lennum = lennum();

        $ordersn = $time . $city_code . $lennum;

        return $ordersn;
    }

    if ($type == 2) {
        $order_id_main = date('YmdHis') . rand(100000, 999999);
        $order_id_len = strlen($order_id_main);
        $order_id_sum = 0;
        for ($i = 0; $i < $order_id_len; $i++) {
            $order_id_sum += (int)(substr($order_id_main, $i, 1));
        }
        $osn = $order_id_main . str_pad((100 - $order_id_sum % 100) % 100, 2, '0', STR_PAD_LEFT);
        return $osn;
    }

}

/**
 * 区号
 */

function cityCode($data)
{
    $los = $data['lat'] . ',' . $data['lng'];

    $url = "https://apis.map.qq.com/ws/geocoder/v1/?location=" . $los . "&key=" . config('MapKey') . "&type=json";

    $res = lmcurl($url);

    $city = string2array($res);


    if ($city['status'] != 0) {

        GetOrderSN(1, $data);

    }
    $ad_info = $city['result']['ad_info'];

    $length = strlen($ad_info['phone_area_code']);

    $city_code = $ad_info['phone_area_code'];

    if ($length > 3) {
        $city_code = substr($city_code, 1, 3);
    }

    return $city_code;
}

/**
 * 根据地址返回坐标
 */
function getLWByAddress($address)
{
    $key = config('wechat.geocodeMap_1');
    $url = 'https://restapi.amap.com/v3/geocode/geo?key=' . $key . '&address=' . urlencode($address);
    $response = file_get_contents($url);
    $jsonResponse = json_decode($response, true);
    if ($jsonResponse['status'] == '1') {
        $jsonResponse['geocodes'][0]['location'] = explode(',', $jsonResponse['geocodes'][0]['location']);
        return json_encode(array(
            'code' => 0,
            'data' => $jsonResponse['geocodes'][0]['location']
        ));
    } else {
        return json_encode(array(
            'code' => -1,
            'data' => $jsonResponse
        ));
    }
}

//生成小程序二维码
function qrcode($value, $page, $width = 600)
{
    try {
        $config = [
            'app_id' => config('wechat.appID'),
            'secret' => config('wechat.AppSecret'),
        ];
        $app = Factory::miniProgram($config);

        $response = $app->app_code->get($page.'?scene='.$value, [
            'width' => $width,
        ]);
//        if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
//            $filename = $response->save('/path/to/directory');
//        }

//        $response = $app->app_code->getUnlimit($value, [
//            'page' => $page,
//            'width' => $width,
//        ]);
        if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
            $filename = $response->save(ROOT_PATH . 'public/uploads/drivingcode', 'qrcode' . time());
            return config('wechat.url') . '/uploads/drivingcode/' . $filename;
        }

        return $response;
    } catch (\Exception $e) {
        return $e->getMessage();
    }
}

function showMsg($status, $message = '', $data = array())
{
    $result = array(
        'status' => $status,
        'message' => $message,
        'data' => $data
    );
    exit(json_encode($result));
}


//发送消息
//function sendMsg($message_cate_id, $title, $content, $member_id)
//{
//    $insert_data = array(
//        'message_cate_id' => $message_cate_id,
//        'title' => $title,
//        'content' => $content,
//        'create_time' => time(),
//        'member_id' => $member_id
//    );
//    Db::name('message')->insertGetId($insert_data);
//}

//发送验证码
function sendVerifyCode($phone)
{
    $code = rand(1000, 9999); // 6位随机验证码
//    Session::set('verify_code'.$phone, $code); // 5分钟过期
    $insert_data = array(
        'name' => $phone,
        'code' => $code,
        'create_time' => time(),
        'effect_time' => time() + 60 * 5,
    );
    $id = Db::name('verify_code')->insertGetId($insert_data);
    Db::name('verify_code')->where([
        ['id', '<>', $id],
        ['name', '=', $phone],
    ])->update([
        'is_del' => 1
    ]);
    sendAliyunSms('86' . $phone,          // 手机号（注意去掉+号）
        '山东省鉴证技术',                 // 短信签名
        'SMS_483315329',         // 模板CODE
        ['code' => $code]);
    return $code;
    // $response = sendSmsCode('13800138000', $code);
}

//检测验证码
function checkCode($phone, $code)
{
    //删除超过5分钟的验证码
    Db::name('verify_code')->where([
        ['name', '=', $phone],
        ['effect_time', '<', time()],
    ])->update([
        'is_del' => 1
    ]);
    $verify_code = Db::name('verify_code')->where([
        ['name', '=', $phone],
        ['is_del', '=', 0],
    ])->order('create_time desc')->find();
    if ($verify_code['code'] != $code) {
        return 0;
    }
//    if (Session::get('verify_code' . $phone) != $code) {
//        return 0;
//    }

    // 验证通过后清除Session
    Db::name('verify_code')->where([['name', '=', $phone],])
        ->update([
            'is_del' => 1
        ]);
//    Session::delete('verify_code'.$phone);
    return 1;
}

//生成token
function generateToken($phone)
{
    // 组合：手机号 + 设备指纹 + 随机字符串
    $deviceFingerprint = $_SERVER['HTTP_USER_AGENT'] ?? 'default';
    $randomStr = bin2hex(random_bytes(8));
    $rawToken = $phone . '|' . $deviceFingerprint . '|' . $randomStr;

    // 加密存储（建议使用hash_hmac）
    return hash_hmac('sha256', $rawToken, 'your_secret_key');
}

//查询使用数量
function useQueryNum($member_id)
{
    $member_account = Db::name('member_account')->where([
        ['count', '>', 0],
        ['effect_data', '>=', time()],
        ['member_id', '=', $member_id],
    ])->order('effect_data')->find();
    if (!$member_account) {
        return -1;
    }
    Db::name('member_account')
        ->where('id', '=', $member_account['id'])
        ->update([
            'count' => Db::raw('count-1'), // 库存减1
            'use_count' => Db::raw('use_count+1')  // 销量加1
        ]);
    return 0;
}

//单条数据转树状数据
function listToTree($list, $pk = 'id', $pid = 'pid', $child = '_child', $root = 0)
{
    $tree = array();// 创建Tree
    if (is_array($list)) {
        // 创建基于主键的数组引用
        $refer = array();
        foreach ($list as $key => $data) {
            $refer[$data[$pk]] =& $list[$key];
        }

        foreach ($list as $key => $data) {
            // 判断是否存在parent
            $parentId = $data[$pid];
            if ($root == $parentId) {
                $tree[$data[$pk]] =& $list[$key];
            } else {
                if (isset($refer[$parentId])) {
                    $parent =& $refer[$parentId];
                    $parent[$child][] =& $list[$key];
                }
            }
        }
    }
    return $tree;
}

//增加余额
function addMoneyc($member_id, $num, $is_count, $order_id, $type = 1)
{
    //1充值 2物价消耗 3汽配消耗 4专家消耗 5评估消耗
    switch ($type) {
        case 1:
            $desc = '充值';
            break;
        case 2:
            $desc = '物价消耗';
            break;
        case 3:
            $desc = '汽配消耗';
            break;
        case 4:
            $desc = '专家消耗';
            break;
        case 5:
            $desc = '评估消耗';
            break;
        default:
            $desc = '物价消耗';
    }
    $insert_data = array(
        'member_id' => $member_id,
        'money' => $num,
        'order_id' => $order_id,
        'is_count' => $is_count,
        'type' => $type,
        'desc' => $desc,
        'create_time' => time()
    );
    if ($is_count == 1) {
        Db::name('member')->where(['id' => $member_id])->setInc('money', $num);
    } else {
        Db::name('member')->where(['id' => $member_id])->setDec('money', $num);
    }
    $insert_id = Db::name('money_record')->insertGetId($insert_data);
    return $insert_id;
}

//随机字符串
function generateRandomString($length = 16)
{
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, strlen($characters) - 1)];
    }
    return $randomString;
}

function generateRandom2($length = 8)
{
    $characters = '0123456789';
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, strlen($characters) - 1)];
    }
    return $randomString;
}

/**
 * 获取openid
 */
function wxLogin($code)
{
    $appId = config('wechat.appID');
    $secret = config('wechat.AppSecret');
    $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $appId . '&secret=' . $secret . '&js_code=' . $code . '&grant_type=authorization_code';
    $res = lmcurl($url);
    return $res;
}

/**
 * @param $request
 * @param $data
 * @return array|PDOStatement|string|\think\Model|null
 * @throws \think\Exception
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 * @throws \think\exception\PDOException
 */
function deuser($ip, $data)
{
    $datas['openid'] = $data['openid'];
    $datas['reg_ip'] = $ip;

    $stmt = Db::name('member_wx')->where('openid', $datas['openid'])->find();
    if ($stmt) {
        $datas['last_login_time'] = time();
        Db::name('member')
            ->where('openid', $datas['openid'])
            ->update($datas);

    } else {
        $datas['create_time'] = time();
        $datas['status'] = 1;

        $user_id = Db::name('member_wx')->insertGetId($datas);
    }
    $member_vx = Db::name('member_wx')->where('openid', $datas['openid'])->find();

    return $member_vx;
}

/**
 * @param $username
 * @param $password
 * @param $tx_phone
 * @param $role
 * @return array|PDOStatement|string|\think\Model|null
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
//增加登录账号
function addMember($username, $password, $tx_phone, $role, $member_wx)
{
    $salt = generateRandomString(8) . generateRandomString(8);
    $member_insert = array(
        'username' => $username,
        'create_time' => time(),
        'password' => encrypt_password(trim($password), $salt),
        'tx_phone' => $tx_phone,
        'role' => $role,
        'salt' => $salt,
    );
    if ($member_wx) {
        $member_insert['member_wx_id'] = $member_wx['id'];
        $member_insert['openid'] = $member_wx['openid'];
    }
    $member_id = Db::name('member')->insertGetId($member_insert);
    $member_info = Db::name('member')->find($member_id);
    return $member_info;
}

/**
 * 获取前天时间戳范围默认昨天
 */
function getTimestamp($day = -1)
{
    $data_string = $day . " day";
    $yesterday = date("Y-m-d", strtotime($data_string));

// 昨天开始时间戳
    $yesterdayStartTimestamp = strtotime($yesterday . " 00:00:00");

// 昨天结束时间戳
    $yesterdayEndTimestamp = strtotime($yesterday . " 23:59:59");

    return array(
        0 => $yesterdayStartTimestamp,
        1 => $yesterdayEndTimestamp
    );
}

/**
 * 本月的时间戳范围
 * @return array
 */
function monthStrtotime()
{
    $firstDayOfMonth = date('Y-m-01'); // 例如：2023-10-01
    $lastDayOfMonth = date('Y-m-t');   // 't' 代表该月的天数，例如：2023-10-31

    $today_start = strtotime($firstDayOfMonth . ' 00:00:00');
    $today_end = strtotime($lastDayOfMonth . ' 23:59:59');
    return array(
        0 => $today_start,
        1 => $today_end
    );
}

//设置金额
function setMoney($member_id,$salesperson_id, $shop_id,$money,$is_count, $order_id=0, $fl=0, $tx_type=0, $type = 1)
{
    //1业务员到账 2商家到账 2业务提现 4商家提现 2业务扣款 4商家扣款 5业务经理到账
    //$tx_type  1线上提现 2三方线下提现 3线下提现
    //$fl 手续费率
    // openid 提现openid; tx_phone 提现手机号 搜索账号获取
    // 1业务员到账 2商家到账 3业务提现 4商家提现 5业务扣款 6商家扣款 7业务经理到账 8业务经理扣款
    //todo 对接微信直接提现
    //todo 第三方提现

    switch ($type) {
        case 1:
            $desc = '业务员到账';
            break;
        case 2:
            $desc = '商家到账';
            break;
        case 3:
            $desc = '业务提现';
            break;
        case 4:
            $desc = '商家提现';
            break;
        case 5:
            $desc = '业务扣款';
            break;
        case 6:
            $desc = '商家扣款';
            break;
        case 7:
            $desc = '业务经理到账';
            break;
        case 8:
            $desc = '业务经理扣款';
            break;
        default:
            $desc = '业务员到账';
    }
    $insert_date = array(
        'member_id'=>$member_id,
        'salesperson_id'=>$salesperson_id,
        'shop_id'=>$shop_id,
        'money' => $money,
        'order_id' => $order_id,
        'is_count' => $is_count,
        'type' => $type,
        'desc' => $desc,
        'tx_type' => $tx_type,
        'create_time' => time(),
    );
    if ($salesperson_id>0){
        $insert_date['role']=1;
    }else{
        $insert_date['role']=2;
    }
    if ($fl>0){
        $sxf=round($money*($fl/100),2);
        $dz_money=$money-$sxf;
    }else{
        $sxf=0;
        $dz_money=$money;
    }
    $insert_date['sxf']=$sxf;
    $insert_date['dz_money']=$dz_money;
    $member_info=Db::name('member')->where([
        ['id','=',$member_id]
    ])->find();
    if ($tx_type==1){
        $insert_date['openid']=$member_info['openid'];
        $insert_date['is_kuan']=2;
        $insert_date['kuan_time']=time();
    }
    if ($tx_type==2){
        $insert_date['tx_phone']=$member_info['tx_phone'];
    }
    //1加 2减
    if ($is_count == 1) {
        if ($salesperson_id>0){
            Db::name('salesperson')->where(['id' => $salesperson_id])->setInc('money', $money);
        }else{
            Db::name('shop')->where(['id' => $shop_id])->setInc('money', $money);
        }
    }else{
        if ($salesperson_id>0){
            Db::name('salesperson')->where(['id' => $salesperson_id])->setDec('money', $money);
        }else{
            Db::name('shop')->where(['id' => $shop_id])->setDec('money', $money);
        }
    }
    $insert_id = Db::name('member_finance')->insertGetId($insert_date);
    return $insert_id;
}

function getTimestampRange($date = '')
{
    // 如果没有传入日期，使用今天
    if (empty($date)) {
        $date = date('Y-m-d');
    }

    // 验证日期格式
    if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $date)) {
        return json(['code' => 400, 'msg' => '日期格式错误，应为 YYYY-MM-DD']);
    }

    // 获取开始时间戳（当天 00:00:00）
    $startTimestamp = strtotime($date . ' 00:00:00');

    // 获取结束时间戳（当天 23:59:59）
    $endTimestamp = strtotime($date . ' 23:59:59');

    // 验证时间戳是否有效
    if ($startTimestamp === false || $endTimestamp === false) {
        return json(['code' => 400, 'msg' => '日期不合法']);
    }
    $return_data[0]=$startTimestamp;
    $return_data[1]=$endTimestamp;

    return $return_data;
}

function getAddressByLocation2($latitude, $longitude)
{
    $key = config('wechat.geocodeMap_ten');
    $nearby = $latitude . ',' . $longitude;
    $url = 'https://apis.map.qq.com/ws/geocoder/v1?location=' . $nearby . '&key=' . $key . '&get_poi=0';
    $response = file_get_contents($url);

    $jsonResponse = json_decode($response, true);

    if ($jsonResponse['status'] == 0) {
        return json_encode(array(
            'code' => 0,
            'data' => $jsonResponse['result']
        ));
    } else {
        return json_encode(array(
            'code' => -1,
            'data' => $jsonResponse['message']
        ));
    }
}

/**
 * @param $yearMonth
 * @return array
 */
function getMonthTimestampRange($yearMonth) {
    // 验证格式
    if (!preg_match('/^\d{4}-\d{2}$/', $yearMonth)) {
        throw new InvalidArgumentException('年月格式错误，应为 YYYY-MM');
    }

    $startTimestamp = strtotime($yearMonth . '-01 00:00:00');

    if ($startTimestamp === false) {
        throw new InvalidArgumentException('无效的年月');
    }

    $endTimestamp = strtotime(date('Y-m-t 23:59:59', $startTimestamp));

    return [
        'start_timestamp' => $startTimestamp,
        'end_timestamp' => $endTimestamp,
        'start_date' => date('Y-m-d H:i:s', $startTimestamp),
        'end_date' => date('Y-m-d H:i:s', $endTimestamp),
        'days_in_month' => date('t', $startTimestamp)
    ];
}
//编辑套餐特殊奖励
function setPackageReward($type,$package_id,$obj_id,$reward=0,$commission=0){
    //type 1商家 2员工
    if ($type==1){
        $package_reward=Db::name('package_reward')->where([
            'is_del'=>0,
            'type'=>1,
            'package_id'=>$package_id,
            'shop_id'=>$obj_id,
        ])->find();
        if ($package_reward){
            $update['id']=$package_reward['id'];
            if ($reward){
                $update['reward1']=$reward;
            }
            if ($commission){
                $update['commission1']=$commission;
            }
            Db::name('package_reward')->update($update);
        }else{
            Db::name('package_reward')->insertGetId([
                'package_id'=>$package_id,
                'shop_id'=>$obj_id,
                'reward1'=>$reward,
                'commission1'=>$commission,
                'create_time'=>time(),
                'type'=>1
            ]);
        }
    }else{
        $package_reward=Db::name('package_reward')->where([
            'is_del'=>0,
            'type'=>2,
            'package_id'=>$package_id,
            'salesperson_id'=>$obj_id,
        ])->find();
        if ($package_reward){
            $update['id']=$package_reward['id'];
            if ($reward){
                $update['reward2']=$reward;
            }
            if ($commission){
                $update['commission2']=$commission;
            }
            Db::name('package_reward')->update($update);
        }else{
            Db::name('package_reward')->insertGetId([
                'package_id'=>$package_id,
                'salesperson_id'=>$obj_id,
                'reward2'=>$reward,
                'commission2'=>$commission,
                'create_time'=>time(),
                'type'=>2
            ]);
        }
    }
}
//财务通过审核设置佣金
function getOrderMoney(){

}
//发送消息
//role 1用户 2商户 3平台
function sendMsg($role,$member_id,$content,$obj_id,$notice_id=0,$re_id=0){
    $insert_data=array(
        'role'=>$role,
        'member_id'=>$member_id,
        'content'=>$content,
        're_id'=>$re_id,
        'notice_id'=>$notice_id,
        'obj_id'=>$obj_id,
        'create_time'=>time()
    );
    return Db::name('msg')->insertGetId($insert_data);
}
// 审核通过后给商家加钱
function orderSendMoney($order_info){
    if ($order_info['status']==1){
        //给员工钱
        $salesperson_info=Db::name('salesperson')->find($order_info['salesperson_id']);
        if ($salesperson_info){
            $member_info=Db::name('member')->where('id','=',$salesperson_info['member_id'])->find();
            $money=round($order_info['reward2']+$order_info['commission2'],2);
            setMoney($member_info['id'],$salesperson_info['id'],0,$money,1,$order_info['id'],0,0,1);

            if ($salesperson_info['top_sid']){
                //给员工上级钱
                $top_salesperson_info=Db::name('salesperson')->find($salesperson_info['top_sid']);
                if ($top_salesperson_info){
                    $top_member_info=Db::name('member')
                        ->where('id','=',$top_salesperson_info['member_id'])
                        ->find();
                    setMoney($top_member_info['id'],$top_salesperson_info['id'],0,$order_info['top_commission2'],1,$order_info['id'],0,0,7);
                }
            }
        }

        //给商家钱
        $shop_info=Db::name('shop')->where('id','=',$order_info['shop_id'])->find();
        if ($shop_info){
            $member_info_shop=Db::name('member')->where('id','=',$shop_info['member_id'])->find();
            $money=round($order_info['reward1']+$order_info['commission1'],2);
            setMoney($member_info_shop['id'],0,$shop_info['id'],$money,1,$order_info['id'],0,0,2);
        }
        Db::name('order')->update([
            'id'=>$order_info['id'],
            'is_fa'=>1,
        ]);
        return 1;
    }else{
        return -1;
    }
}

//获取前6个月
function getLastSixMonths() {
    $months = [];
    $current = new DateTime();

    // 从当前月份开始，往前推5个月
    for ($i = 5; $i >= 0; $i--) {
        $date = new DateTime();
        $date->modify("first day of -$i months");

        $months[] = [
            'year' => $date->format('Y'),
            'month' => $date->format('m月'),
            'month_name' => $date->format('F'),
            'display' => $date->format('Y年m月'),
            'display2' => $date->format('Y-m')
        ];
    }
    return $months;
}
//发送订单 套餐id
function getPackageMoney($pack_id,$order_id){
    $order_info=Db::name('order')->find($order_id);
    $pack_info=Db::name('package')->find($pack_id);
    //salesperson_id shop_id
    //    `reward1`   '商家奖励',
    //  `reward2`   '业务员奖励',
    //  `commission1`   '商家佣金',
    //  `commission2`   '业务员佣金',
    //  `sc_money`   '首冲金额',
    $shop_pack_money=Db::name('package_reward')->where([
        ['type','=',1],
        ['is_del','=',0],
        ['package_id','=',$pack_id],
        ['shop_id','=',$order_info['shop_id']],
    ])->find();
    $sa_pack_money=Db::name('package_reward')->where([
        ['type','=',2],
        ['is_del','=',0],
        ['package_id','=',$pack_id],
        ['salesperson_id','=',$order_info['salesperson_id']],
    ])->find();
    if ($shop_pack_money){
        $pack_info['reward1']=$shop_pack_money['reward1'];
        $pack_info['commission1']=$shop_pack_money['commission1'];
    }
    if ($sa_pack_money){
        $pack_info['reward2']=$sa_pack_money['reward2'];
        $pack_info['commission2']=$sa_pack_money['commission2'];
    }
    return $pack_info;
}

function convertToWebP($originalPath, $quality = 80)
{
    if (!file_exists($originalPath)) {
        return false;
    }

    $fileInfo = getimagesize($originalPath);
    if (!$fileInfo) {
        return false;
    }

    $mimeType = $fileInfo['mime'];
    $webpPath = pathinfo($originalPath, PATHINFO_DIRNAME) . '/' .
        pathinfo($originalPath, PATHINFO_FILENAME) . '.webp';

    switch ($mimeType) {
        case 'image/jpeg':
            $image = imagecreatefromjpeg($originalPath);
            break;
        case 'image/png':
            $image = imagecreatefrompng($originalPath);
            // 处理PNG透明度
            imagepalettetotruecolor($image);
            imagealphablending($image, true);
            imagesavealpha($image, true);
            break;
        case 'image/gif':
            $image = imagecreatefromgif($originalPath);
            break;
        case 'image/webp':
            // 如果已经是webp格式，直接返回原路径
            return $originalPath;
        default:
            return false;
    }

    if (!$image) {
        return false;
    }

    // 转换为WebP格式
    $result = imagewebp($image, $webpPath, $quality);
    imagedestroy($image);

    if ($result && file_exists($webpPath)) {
        return $webpPath;
    }
    return false;
}
//








